"""
生成测试数据脚本
创建时间：2025-09-17
作者：开发团队
目的：生成用于测试统计分析功能的模拟数据
"""

import random
from datetime import datetime, timedelta, timezone
from sqlalchemy.orm import Session
from ..core.database import SessionLocal
from ..models.user import User
from ..models.campus import Campus
from ..models.verification import VerificationRecord
from ..models.special_visitor import SpecialVisitor
from ..utils.logger import get_logger

# 获取日志记录器
logger = get_logger(__name__)

# 姓名列表
NAMES = [
    "张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十",
    "郑一", "王二", "冯三", "陈四", "褚五", "卫六", "蒋七", "沈八",
    "韩九", "杨十", "朱一", "秦二", "尤三", "许四", "何五", "吕六"
]

# 公司列表
COMPANIES = [
    "科技有限公司", "贸易公司", "建筑工程公司", "文化传媒公司", 
    "金融服务公司", "教育培训公司", "医疗健康公司", "餐饮管理公司"
]

# 访问目的列表
PURPOSES = [
    "商务洽谈", "技术交流", "产品展示", "合作签约",
    "项目考察", "售后服务", "会议参会", "培训学习"
]

# 特殊访客类型
SPECIAL_TYPES = ["VIP", "纠纷", "其他"]

# 院区名称
CAMPUS_NAMES = ["总部院区", "东区院区", "西区院区", "南区院区", "北区院区"]

def create_campuses(db: Session):
    """创建院区数据"""
    try:
        # 检查是否已存在院区数据
        existing_campuses = db.query(Campus).count()
        if existing_campuses > 0:
            logger.info("院区数据已存在，跳过创建")
            return
        
        # 创建院区
        for name in CAMPUS_NAMES:
            campus = Campus(
                name=name,
                address=f"{name}详细地址"
            )
            db.add(campus)
        
        db.commit()
        logger.info(f"成功创建 {len(CAMPUS_NAMES)} 个院区")
    except Exception as e:
        db.rollback()
        logger.error(f"创建院区数据失败: {str(e)}")
        raise

def create_users(db: Session):
    """创建用户数据（门卫）"""
    try:
        # 检查是否已存在门卫数据
        existing_guards = db.query(User).filter(User.role == "guard").count()
        if existing_guards > 0:
            logger.info("门卫数据已存在，跳过创建")
            return
        
        # 获取所有院区
        campuses = db.query(Campus).all()
        if not campuses:
            logger.warning("没有院区数据，无法创建门卫")
            return
        
        # 为每个院区创建2个门卫
        for campus in campuses:
            for i in range(2):
                username = f"guard_{campus.id}_{i+1}"
                user = User(
                    username=username,
                    password_hash="$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBPj/RK.PZvO.S",  # 默认密码: admin123
                    name=f"{campus.name}门卫{i+1}",
                    role="guard",
                    phone=f"138{random.randint(10000000, 99999999)}",
                    campus_id=campus.id
                )
                db.add(user)
        
        db.commit()
        logger.info(f"成功创建 {len(campuses) * 2} 个门卫账户")
    except Exception as e:
        db.rollback()
        logger.error(f"创建用户数据失败: {str(e)}")
        raise

def generate_verification_records(db: Session, count: int = 1000):
    """生成访客核验记录"""
    try:
        # 获取所有门卫
        guards = db.query(User).filter(User.role == "guard").all()
        if not guards:
            logger.warning("没有门卫数据，无法生成核验记录")
            return
        
        # 获取所有院区
        campuses = db.query(Campus).all()
        if not campuses:
            logger.warning("没有院区数据，无法生成核验记录")
            return
        
        # 生成核验记录
        for i in range(count):
            # 随机选择门卫
            guard = random.choice(guards)
            
            # 随机生成访客信息
            visitor_name = random.choice(NAMES)
            visitor_phone = f"13{random.randint(1000000000, 9999999999)}"
            visitor_id_card = f"{random.randint(100000000000000000, 999999999999999999)}"
            visitor_company = random.choice(COMPANIES)
            
            # 随机生成被访人信息
            host_name = random.choice(NAMES)
            host_phone = f"13{random.randint(1000000000, 9999999999)}"
            
            # 随机生成访问时间和目的
            visit_purpose = random.choice(PURPOSES)
            
            # 随机生成访问时间（最近30天内）
            days_ago = random.randint(0, 30)
            visit_time = datetime.now(timezone.utc) - timedelta(days=days_ago, hours=random.randint(0, 23), minutes=random.randint(0, 59))
            
            # 随机生成核验时间（访问时间之后）
            verification_time = visit_time + timedelta(minutes=random.randint(5, 60))
            
            # 随机生成核验结果
            result = random.choices(["approved", "rejected"], weights=[0.85, 0.15])[0]
            rejection_reason = None
            if result == "rejected":
                rejection_reason = random.choice(["证件不符", "预约信息错误", "黑名单", "其他原因"])
            
            # 随机生成是否为特殊访客
            is_special = random.choices([True, False], weights=[0.1, 0.9])[0]
            special_type = None
            if is_special:
                special_type = random.choice(SPECIAL_TYPES)
            
            # 创建核验记录
            record = VerificationRecord(
                visitor_name=visitor_name,
                visitor_phone=visitor_phone,
                visitor_id_card=visitor_id_card,
                visitor_company=visitor_company,
                host_name=host_name,
                host_phone=host_phone,
                visit_time=visit_time,
                purpose=visit_purpose,
                verification_time=verification_time,
                guard_id=guard.id,
                result=result,
                rejection_reason=rejection_reason,
                is_special=is_special,
                special_type=special_type,
                qr_data="test_qr_data"
            )
            
            db.add(record)
            
            # 每100条记录提交一次
            if (i + 1) % 100 == 0:
                db.commit()
                logger.info(f"已生成 {i + 1} 条核验记录")
        
        db.commit()
        logger.info(f"成功生成 {count} 条访客核验记录")
    except Exception as e:
        db.rollback()
        logger.error(f"生成访客核验记录失败: {str(e)}")
        raise

def generate_special_visitors(db: Session, count: int = 50):
    """生成特殊访客数据"""
    try:
        # 获取所有院区
        campuses = db.query(Campus).all()
        if not campuses:
            logger.warning("没有院区数据，无法生成特殊访客")
            return
        
        # 生成特殊访客
        for i in range(count):
            # 随机选择院区
            campus = random.choice(campuses)
            
            # 随机生成访客信息
            name = random.choice(NAMES)
            phone = f"13{random.randint(1000000000, 9999999999)}"
            id_card = f"{random.randint(100000000000000000, 999999999999999999)}"
            visitor_type = random.choice(SPECIAL_TYPES)
            
            # 随机生成有效期（未来30-365天）
            valid_days = random.randint(30, 365)
            valid_until = (datetime.now(timezone.utc) + timedelta(days=valid_days)).date()
            
            # 随机生成备注
            remarks = random.choice(["重要客户", "需要特别关注", "历史问题访客", "合作伙伴", ""])
            
            # 创建特殊访客记录
            visitor = SpecialVisitor(
                name=name,
                phone=phone,
                id_card=id_card,
                type=visitor_type,
                valid_until=valid_until,
                remarks=remarks,
                campus_id=campus.id
            )
            
            db.add(visitor)
            
            # 每20条记录提交一次
            if (i + 1) % 20 == 0:
                db.commit()
                logger.info(f"已生成 {i + 1} 条特殊访客记录")
        
        db.commit()
        logger.info(f"成功生成 {count} 条特殊访客记录")
    except Exception as e:
        db.rollback()
        logger.error(f"生成特殊访客记录失败: {str(e)}")
        raise

def main():
    """主函数"""
    logger.info("开始生成测试数据...")
    
    # 获取数据库会话
    db = SessionLocal()
    
    try:
        # 创建院区数据
        create_campuses(db)
        
        # 创建用户数据
        create_users(db)
        
        # 生成访客核验记录
        generate_verification_records(db, 1000)
        
        # 生成特殊访客数据
        generate_special_visitors(db, 50)
        
        logger.info("测试数据生成完成")
    except Exception as e:
        logger.error(f"生成测试数据失败: {str(e)}")
    finally:
        db.close()

if __name__ == "__main__":
    main()